package cn.zshprint.serein.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上传跑龙套
 *
 * @author zshprint
 * @date 2021/07/28
 */
@PropertySource("ossconfig.properties")
@Component
public class UploadUtils {
    /**
     * 端点
     */
    @Value("${ENDPOINT}")
    private String ENDPOINT;
    /**
     * 访问密钥id
     */
    @Value("${ACCESS_KEY_ID}")
    private String ACCESS_KEY_ID;
    /**
     * 访问密钥的秘密
     */
    @Value("${ACCESS_KEY_SECRET}")
    private String ACCESS_KEY_SECRET;
    /**
     * bucket名称
     */
    @Value("${BUCKET_NAME}")
    private String BUCKET_NAME;
    /**
     * 遭受url
     */
    @Value("${SUFFER_URl}")
    private String SUFFER_URl;
    /**
     * 自卫队
     */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");


    /**
     * 得到ossclient
     *
     * @return {@link OSSClient}
     */
    public OSSClient getOSSClient() {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        if (ossClient.doesBucketExist(BUCKET_NAME)) {
            System.out.println("bucket exist");
        } else {
            System.out.println("创建新的bucket");
            CreateBucketRequest buildRequest = new CreateBucketRequest(null);
            buildRequest.setBucketName(BUCKET_NAME);
            buildRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(buildRequest);
            ossClient.shutdown();
        }
        return ossClient;
    }

    /**
     * 上传文档
     *
     * @param multipartFile 多部分文件
     * @return {@link String}
     */
    public String uploadDocument(MultipartFile multipartFile) {
        OSSClient ossClient = this.getOSSClient();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String date = sdf.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = suffix + "/" + date + "/" + uuid + suffix;
        String url = null;
        try {
            ossClient.putObject(BUCKET_NAME, fileName, new ByteArrayInputStream(multipartFile.getBytes()));
            url = SUFFER_URl + fileName;
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }
}
